<template>
  <div class="certification-review">
    <h2>认证审核</h2>

    <!-- 如果有路由参数 id，直接显示单条记录 -->
    <el-card v-if="certificationData && fromId" class="review-card">
      <div slot="header" class="clearfix">
        <span>用户ID: {{ certificationData.id }}</span>
        <el-tag :type="getStatusType(certificationData.isOk)">{{ getStatusText(certificationData.isOk) }}</el-tag>
      </div>

      <el-descriptions title="认证信息" :column="1" border>
        <el-descriptions-item label="身份证正面">
          <el-image
            v-if="certificationData.idCardRight"
            :src="certificationData.idCardRight"
            style="width: 200px; height: 120px"
            :preview-src-list="[certificationData.idCardRight]"
          />
          <span v-else>未上传</span>
        </el-descriptions-item>
        <el-descriptions-item label="身份证反面">
          <el-image
            v-if="certificationData.idCardBack"
            :src="certificationData.idCardBack"
            style="width: 200px; height: 120px"
            :preview-src-list="[certificationData.idCardBack]"
          />
          <span v-else>未上传</span>
        </el-descriptions-item>
        <el-descriptions-item label="营业执照">
          <el-image
            v-if="certificationData.businessLicense"
            :src="certificationData.businessLicense"
            style="width: 200px; height: 120px"
            :preview-src-list="[certificationData.businessLicense]"
          />
          <span v-else>未上传</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 未通过原因输入框 -->
      <el-form v-if="showReasonInput" ref="reasonForm" :model="reasonForm" :rules="reasonRules" label-width="100px">
        <el-form-item label="未通过原因" prop="reason">
          <el-input v-model="reasonForm.reason" type="textarea" :rows="3" placeholder="请输入未通过原因"></el-input>
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <div class="action-buttons" v-if="certificationData.isOk === 0">
        <el-button type="success" @click="handlePass">通过认证</el-button>
        <el-button type="danger" @click="showReasonInput = true" v-if="!showReasonInput">不通过</el-button>
        <el-button type="danger" @click="handleUnpass" v-if="showReasonInput">确认不通过</el-button>
        <el-button @click="showReasonInput = false" v-if="showReasonInput">取消</el-button>
      </div>
    </el-card>

    <!-- 如果没有 id，显示列表 -->
    <template v-else>
      <el-table :data="certificationData" border style="width: 100%" v-loading="loading" @row-click="handleRowClick">
        <el-table-column prop="id" label="用户ID" width="100"></el-table-column>
        <el-table-column label="认证状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.isOk)">{{ getStatusText(scope.row.isOk) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="身份证正面" width="200">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.idCardRight"
              :src="scope.row.idCardRight"
              style="width: 100px; height: 60px"
              :preview-src-list="[scope.row.idCardRight]"
            />
            <span v-else>未上传</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="handleRowClick(scope.row)">审核</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 弹窗显示选中记录详情 -->
      <el-dialog title="认证详情" :visible.sync="dialogVisible" width="50%">
        <el-card v-if="selectedCertification" class="review-card">
          <div slot="header" class="clearfix">
            <span>用户ID: {{ selectedCertification.id }}</span>
            <el-tag :type="getStatusType(selectedCertification.isOk)">{{ getStatusText(selectedCertification.isOk) }}</el-tag>
          </div>

          <el-descriptions title="认证信息" :column="1" border>
            <el-descriptions-item label="身份证正面">
              <el-image
                v-if="selectedCertification.idCardRight"
                :src="selectedCertification.idCardRight"
                style="width: 200px; height: 120px"
                :preview-src-list="[selectedCertification.idCardRight]"
              />
              <span v-else>未上传</span>
            </el-descriptions-item>
            <el-descriptions-item label="身份证反面">
              <el-image
                v-if="selectedCertification.idCardBack"
                :src="selectedCertification.idCardBack"
                style="width: 200px; height: 120px"
                :preview-src-list="[selectedCertification.idCardBack]"
              />
              <span v-else>未上传</span>
            </el-descriptions-item>
            <el-descriptions-item label="营业执照">
              <el-image
                v-if="selectedCertification.businessLicense"
                :src="selectedCertification.businessLicense"
                style="width: 200px; height: 120px"
                :preview-src-list="[selectedCertification.businessLicense]"
              />
              <span v-else>未上传</span>
            </el-descriptions-item>
          </el-descriptions>

          <el-form v-if="showReasonInput" ref="reasonForm" :model="reasonForm" :rules="reasonRules" label-width="100px">
            <el-form-item label="未通过原因" prop="reason">
              <el-input v-model="reasonForm.reason" type="textarea" :rows="3" placeholder="请输入未通过原因"></el-input>
            </el-form-item>
          </el-form>

          <div class="action-buttons" v-if="selectedCertification.isOk === 0">
            <el-button type="success" @click="handlePass">通过认证</el-button>
            <el-button type="danger" @click="showReasonInput = true" v-if="!showReasonInput">不通过</el-button>
            <el-button type="danger" @click="handleUnpass" v-if="showReasonInput">确认不通过</el-button>
            <el-button @click="showReasonInput = false" v-if="showReasonInput">取消</el-button>
          </div>
        </el-card>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import { getCertificationList, passCertification, unpassCertification, getCertificationById } from '@/api/auth/auth';

export default {
  name: 'CertificationReview',
  data() {
    return {
      certificationData: null, // 单条记录或列表
      selectedCertification: null, // 选中的认证记录（列表模式）
      dialogVisible: false, // 控制弹窗显示
      showReasonInput: false, // 控制未通过原因输入框
      loading: false, // 表格加载状态
      fromId: false, // 是否通过路由参数加载单条记录
      reasonForm: {
        reason: '',
      },
      reasonRules: {
        reason: [{ required: true, message: '请输入未通过原因', trigger: 'blur' }],
      },
    };
  },
  created() {
    const id = this.$route.query.id; // 获取路由参数 id
    if (id) {
      this.fromId = true;
      this.fetchCertificationById(id); // 加载单条记录
    } else {
      this.fetchCertificationData(); // 加载列表
    }
  },
  methods: {
    // 获取认证列表
    async fetchCertificationData() {
      this.loading = true;
      try {
        const response = await getCertificationList();
        console.log('获取认证数据', response);
        this.certificationData = response.rows; // 存储列表
      } catch (error) {
        this.$message.error('获取认证数据失败');
        console.error('获取认证数据失败', error);
      } finally {
        this.loading = false;
      }
    },

    // 根据 id 获取单条认证记录
    async fetchCertificationById(id) {
      this.loading = true;
      try {
        const response = await getCertificationById(id);
        console.log('获取单条认证数据', response);
        this.certificationData = response; // 存储单条记录
      } catch (error) {
        this.$message.error('获取认证详情失败');
        console.error('获取认证详情失败', error);
      } finally {
        this.loading = false;
      }
    },

    // 点击行或按钮选择记录（列表模式）
    handleRowClick(row) {
      console.log("row:",row)
      this.selectedCertification = row;
      console.log("row:",this.selectedCertification)
      this.dialogVisible = true;
      this.showReasonInput = false;
      this.reasonForm.reason = '';
    },

    // 处理认证通过
    async handlePass() {
      const id = this.fromId ? this.certificationData.id : this.selectedCertification.id; // 根据模式选择 id
      this.$confirm('确认通过该用户的认证吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            console.log('认证通过', id);
            await passCertification(id);
            this.$message.success('认证通过成功');
            if (this.fromId) {
              this.fetchCertificationById(id); // 刷新单条记录
            } else {
              this.dialogVisible = false;
              this.fetchCertificationData(); // 刷新列表
            }
          } catch (error) {
            this.$message.error('认证通过失败');
            console.error('认证通过失败', error);
          }
        })
        .catch(() => {
          this.$message.info('已取消操作');
        });
    },

    // 处理认证不通过
    async handleUnpass() {
      const id = this.fromId ? this.certificationData.id : this.selectedCertification.id; // 根据模式选择 id
      this.$refs.reasonForm.validate(async (valid) => {
        if (valid) {
          this.$confirm('确认拒绝该用户的认证吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(async () => {
              try {
                // 将 id 和 reason 封装成对象传递
                const requestData = { id, reason: this.reasonForm.reason };
                await unpassCertification(id, requestData);
                console.log('认证拒绝', id, this.reasonForm.reason);
                this.$message.success('认证拒绝成功');
                if (this.fromId) {
                  this.fetchCertificationById(id); // 刷新单条记录
                } else {
                  this.dialogVisible = false;
                  this.fetchCertificationData(); // 刷新列表
                }
                this.showReasonInput = false; // 成功后隐藏输入框
                this.reasonForm.reason = ''; // 清空输入框
              } catch (error) {
                this.$message.error('认证拒绝失败');
                console.error('认证拒绝失败', error);
              }
            })
            .catch(() => {
              this.$message.info('已取消操作');
            });
        } else {
          this.$message.error('请填写未通过原因');
        }
      });
    },

    // 根据 isOk 返回状态文本
    getStatusText(isOk) {
      switch (isOk) {
        case 0:
          return '待审核';
        case 1:
          return '已通过';
        case 2:
          return '未通过';
        default:
          return '未知';
      }
    },

    // 根据 isOk 返回标签类型
    getStatusType(isOk) {
      switch (isOk) {
        case 0:
          return 'warning';
        case 1:
          return 'success';
        case 2:
          return 'danger';
        default:
          return 'info';
      }
    },
  },
};
</script>

<style scoped>
.certification-review {
  padding: 20px;
}

.review-card {
  width: 100%;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-buttons {
  margin-top: 20px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 10px;
}
</style>
